package com.wlstock.funi.runnable;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.baidu.tts.loopj.HttpGet;
import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.ToastUtils;


public class ZXRealPrice {
	public static final int BSFLAG_BUY = 1;
	public static final int BSFLAG_SAILE = 2;
	private int bsFlag;
	private String stkCode;
	public PriceListener pListener;
	private ZXRealPrice(){};
	public ZXRealPrice(int bsFlag, String stkCode) {
		super();
		this.bsFlag = bsFlag;
		this.stkCode = stkCode;
	}
	
	public void request(){
		if (!FundApplication.isLogSuccess) {
			NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_LOG_OUTDATE, "登陆失效，请重新登陆", "无法获取最新价格", R.drawable.ic_exception);
			ToastUtils.showMiddleMsg(FundApplication.getInstance(), "尚未登录，无法获取最新价格");
			return;
		}
		StringBuffer requestSB = new StringBuffer();
		requestSB.append("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getHQ&stkcode=").append(stkCode).append("&bsflag=").append(bsFlag).append("&bsprop=0");
		
		FundAsyTask<String, Void, List<String>> priceTask = new FundAsyTask<String, Void, List<String>>();
		priceTask.backListener = new TaskLitener<String, List<String>>() {

			@Override
			public List<String> doInBackground(String... params) {
				HttpGet curSrkGet = new HttpGet(params[0]);
				HttpClient client = new DefaultHttpClient();
				try {
					curSrkGet.addHeader("Accept-Encoding", "gzip, deflate");
					curSrkGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
					curSrkGet.addHeader("Connection", "keep-alive");
					curSrkGet.addHeader("Content-Type", "text/plain;charset=UTF-8");
					curSrkGet.addHeader("Cookie", FundApplication.cookie);
					curSrkGet.addHeader("Referer", "https://etrade.cs.ecitic.com/ymtrade/stock/sale.jsp");
					curSrkGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");

					HttpResponse stkDetailResponse = client.execute(curSrkGet);
					if (stkDetailResponse.getStatusLine().getStatusCode() == 200) {
						String response = IOUtils.is2Str(stkDetailResponse.getEntity().getContent());
						Log.i("TAG", response);
						return parse(response);
					}else{
						FundApplication.isLogSuccess = false;
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		}; 
		
		priceTask.resultListener = new TaskResultListener<List<String>>() {

			@Override
			public void onPostResult(List<String> result) {
				// TODO Auto-generated method stub
				if (pListener!=null) {
					if (result!=null && result.size()==14) {
						pListener.onUpdatePriceSuccess(result);
					}else {
						pListener.onUpdatePriceSuccess(null);
					}
				}
			}
		};
		priceTask.execute(requestSB.toString());
	}

	private List<String> parse(String response) {
		// TODO Auto-generated method stub
		List<String> tmpList = new ArrayList<String>();
		Pattern compile = Pattern.compile(">\\d{1,}\\.\\d{2}");
		Matcher matcher = compile.matcher(response);
		while(matcher.find()){
			String tmpStr = response.substring(matcher.start()+1, matcher.end());
			if (tmpStr!=null) {
				tmpList.add(tmpStr);	
			}
		}
		return tmpList;
	}
	
	public interface PriceListener{
		public void onUpdatePriceSuccess(List<String> priList);
	}
	

}

//https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getHQ&stkcode=603599&bsflag=2&bsprop=0  卖出拿当前股票详情
//https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getHQ&stkcode=603599&bsflag=1&bsprop=0  买入拿当前股票详情

//method:getHQ
//stkcode:603998
//bsflag:2
//bsprop:0

//Accept:*/*
//Accept-Encoding:gzip, deflate
//Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
//Connection:keep-alive
//Content-Length:0
//Content-Type:text/plain;charset=UTF-8
//Cookie:JSESSIONID=qlPgWgPGySvvDzB0Zpts9xPpyYqZBFCh5446w2FMs6PgFy121lJ2!297676372!-908755652; ssl=etrade-ssl-2
//Host:etrade.cs.ecitic.com
//Origin:https://etrade.cs.ecitic.com
//Referer:https://etrade.cs.ecitic.com/ymtrade/stock/sale.jsp
//User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

//获取卖出详情返回结果 
//<script language="javascript">
//jHideMsg();    //出错会有这个 jShowMsg('error',"证券代码（603557）不存在");
//</script>
//
//<script language="javascript">
//setData("secuid","A303112208");
//setData("stkname","方盛制药");
//setData("price","48.61");
//
//setData("price","48.61");
//
//setData("cj","27224");
//setData("zx","48.61");
//setData("zt","51.47");
//setData("dt","42.11");
//setData("zs","46.79");
//
//setData("stktype","GP");
//setData("digit","2");
//setData("exchange","1");
//
//setData("maxQty","200");
//setData("fundavl","36253.33");
//setData("costprice","48.61");
//
//Add by yidong 2009.8.8新股标志
//setData("zqzt","0");
//</script>
//<table class="hq">
//    <tr>
//      <td width="21%" class="lbg">卖五</td>
//      <td width="36%" class="handler red">48.70</td>
//      <td colspan="2" style="text-align:right">22</td>
//    </tr>
//    <tr>
//      <td class="lbg">卖四</td>
//      <td class="handler red">48.69</td>
//      <td colspan="2" style="text-align:right">11</td>
//    </tr>
//    <tr>
//      <td class="lbg">卖三</td>
//      <td class="handler red">48.63</td>
//      <td colspan="2" style="text-align:right">20</td>
//    </tr>
//    <tr>
//      <td class="lbg">卖二</td>
//      <td class="handler red">48.62</td>
//      <td colspan="2" style="text-align:right">40</td>
//    </tr>
//    <tr>
//      <td class="lbg">卖一</td>
//      <td class="handler red">48.61</td>
//      <td colspan="2" style="text-align:right">23</td>
//    </tr>
//    <tr>
//      <td height="1" colspan="4"></td>
//      </tr>
//    <tr>
//      <td class="lbg">买一</td>
//      <td class="handler red">48.60</td>
//      <td colspan="2" style="text-align:right">38</td>
//    </tr>
//    <tr>
//      <td class="lbg">买二</td>
//      <td class="handler red">48.59</td>
//      <td colspan="2" style="text-align:right">23</td>
//    </tr>
//    <tr>
//      <td class="lbg">买三</td>
//      <td class="handler red">48.58</td>
//      <td colspan="2" style="text-align:right">41</td>
//    </tr>
//    <tr>
//      <td class="lbg">买四</td>
//      <td class="handler red">48.56</td>
//      <td colspan="2" style="text-align:right">6</td>
//    </tr>
//    <tr>
//      <td class="lbg">买五</td>
//      <td class="handler red">48.52</td>
//      <td colspan="2" style="text-align:right">16</td>
//    </tr>
//    <tr>
//      <td colspan="4" height="1"></td>
//      </tr>
//    <tr>
//      <td class="lbg">现价</td>
//      <td class="handler red">48.61</td>
//      <td class="lbg">涨停</td>
//      <td class="handler red">51.47</td>
//    </tr>
//    <tr>
//      <td class="lbg">昨收</td>
//      <td>46.79</td>
//      <td width="17%" class="lbg">跌停</td>
//      <td class="handler green">42.11</td>
//    </tr>
//  </table>
